from selenium import webdriver
from selenium.webdriver.common.action_chains import ActionChains
from selenium.webdriver.common.by import By
import json
import pathlib
from loger import Logger
from selenium.webdriver.chrome.options import Options
from selenium.webdriver.chrome.service import Service
import time
import random
root=pathlib.Path(__file__).parent
log = Logger('user-zt.shzenon.cn',StreamLevel='debug',FileLevel='info').logger

browser=None
def init(url):
    global browser
    chrome_options = Options()
    # chrome_options.add_experimental_option("debuggerAddress", "127.0.0.1:9222")
    chrome_options.add_argument("--ignore-certificate-errors")
    chrome_options.binary_location=r"D:\chrome-win64\chrome.exe"
    service=Service(str(root/"chromedriver.exe"))
    browser = webdriver.Chrome(service=service, options=chrome_options)
    # browser = webdriver.Chrome(options=chrome_options)
    browser.get(url)
    # browser.maximize_window()
    browser.implicitly_wait(15)
    return browser

def findxpath(xpath,t=3):
    global browser
    browser.implicitly_wait(t)
    try:
        result = browser.find_element(By.XPATH,xpath)
    except :
        log.info("not find xpath!")
        result= None

    return result

def tjs(js):
    try:
        obj = browser.execute_script(js)
    except:
        log.debug(f"执行失败:{js}")
        return False
    else:
        log.debug(f"执行成功:{js}")
        return obj
def findlinktext(text,t=5):
    global browser
    browser.implicitly_wait(t)
    try:
        result = browser.find_element(By.LINK_TEXT,text)
    except :
        log.info("not find linktext!")
        result= None
    return result
def clickobj(obj):
    global browser
    if obj is None :return False
    actions = ActionChains(browser)
    actions.move_to_element(obj)
    actions.click(obj)
    actions.perform()

# 初始化浏览器
def saveCookies():
    cookies = browser.get_cookies()
    # 保存 Cookie 到文件
    print(cookies)
    with open("cookies.json", "w", encoding="utf-8") as f:
        json.dump(cookies, f, ensure_ascii=False, indent=2)
def msleep(a=2,b=5):
    time.sleep(random.random()*(b-a)+a)

def tryclick(xpath):
    try:
        browser.find_element(By.XPATH,xpath).click()
    except:
        log.debug(f"点击失败:{xpath}")
        return False
    else:
        log.debug(f"点击成功:{xpath}")
        return True
    
def login():
    setLocalStorage("zt",'''{"state":{"u":{"id":456274,"orgCode":"3153000590","systemType":"3","token":"eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ1c2VybmFtZSI6IjUzMDYyMTIwMTAwODMxMjAyNSIsImV4cCI6MTc2NDA1NDU2MX0.ySO9jZQJagWlKbwynW5gRYG9tKWhhrqAfJAPwjRIg74","userCode":"XL2023111523563177898190","userName":"蒋雨","userSex":"2","userType":"1"}},"version":0}''')
def setLocalStorage(key:str,val:str):
    browser.execute_script(f"localStorage.setItem('{key}', '{val}');")

def step1():
    p=0
    time.sleep(0.5)
    while(not tryclick("/html/body/div[2]/div/main/div[3]/div[1]/div/button")):
        time.sleep(1)
    time.sleep(0.3)
    # obj=findlinktext("立即测试")
    # clickobj(obj)
    titlelists=["基本情况-(2024-2025)",
                "自我情况（一）-（2024-2025)",
                "自我情况（二）-（2024-2025)",
                "自我情况（三）-（2024-2025)",
                "自我情况（四）-（2024-2025)",
                "自我情况（五）-（2024-2025)",
                "校园情况（一）-（2024-2025)",
                "校园情况（二）-(2024-2025)",
                "校园情况（三）-（2024-2025)",
                "校园情况（四）-（2024-2025)",
                "家庭情况（一）-（2024-2025)",
                "家庭情况（二）-（2024-2025)"
                ]
    while(1):
        time.sleep(0.3)
        obj=findxpath("/html/body/div[2]/div/main/div[3]/div[1]")
        if(obj is None): continue
        titleText=obj.text
        if(titleText in titlelists ):
            p=titlelists.index(titleText)+1
        else:
            p=0
        '''
        p=0
        if(titleText =="基本情况-(2024-2025)"):
            p=1
        if(titleText =="自我情况（一）-（2024-2025)"):
            p=2
        if(titleText =="自我情况（二）-（2024-2025)"):
            p=3
        if(titleText =="自我情况（三）-（2024-2025)"):
            p=4
        if(titleText =="自我情况（四）-（2024-2025)"):
            p=5
        if(titleText =="自我情况（五）-（2024-2025)"):
            p=6
        if(titleText =="校园情况（一）-（2024-2025)"):
            p=7
        if(titleText =="校园情况（二）-(2024-2025)"):
            p=8
        if(titleText =="校园情况（三）-（2024-2025)"):
            p=9
        if(titleText =="校园情况（四）-（2024-2025)"):
            p=10
        if(titleText =="家庭情况（一）-（2024-2025)"):
            p=11
        if(titleText =="家庭情况（二）-（2024-2025)"):
            p=12
        '''
        print(p)
        if(p>0):selectoption(p)

def selectoption(id:int):
    jsonsrt=tjs("return localStorage.getItem('zt');")
    userinfo=json.loads(jsonsrt)
    ans={   1:[1,2,1,1,0,0,3,0,0]
        ,   2:[0,0,0,0,0,0,0,2,0,0,0,2,0,0,0,2,0,2,0,0,0]
        ,   3:[0,0,0,0,0,
               0,0,0,0,0,
               0,0,0,0,0,
               0,0,0,0,0,
               0,0,0,0,0,
               0,0,0,0,0,
               0,0,0,0,0,
               0,0,0,0,0,
               0,0,0
               ]
        ,   4:[3,3,3,3,3,3,3]
        ,   5:[3,3,3,3,2,2]
        ,   6:[0,0,0,0,0,0,0,0,0]
        ,   7:[0,1,0,1,0,0,1,0,0]
        ,   8:[0,0,0,0,0,0,0]
        ,   9:[0,1,0,1,1,1,0,0]
        ,   10:[0,0,0,0,0,0,0,0,0,0,0,0,0,0]
        ,   11:[0,0,0,0,0,0,0,0]
        ,   12:[0,3,0,0,3,
                0,3,0,0,1,
                0,0,3,0,0,
                3,0,0,3,3,
                0,4,3,3,3]

         
         }
    ans[1][1]=int(userinfo['state']['u']['userSex'])-1
    time.sleep(0.3)
    tryclick("/html/body/div[2]/div/main/div[3]/div[4]/button")
    time.sleep(1)
    for i in ans[id]:
        tjs(f"s=document.getElementsByClassName('overflow-y-auto')[0].children;s[{i}].click();")
        # msleep()
        time.sleep(1)
    while(1):
        span_element = findxpath("/html/body/div[2]/div/main/div[5]/button[2]")
        if span_element is None : 
            break
        else:
            print(f"wait!{time.time()}")
            time.sleep(0.5)


if __name__ == '__main__':

    init("https://user-zt.shzenon.cn/login")
    # login()
    browser.get("https://user-zt.shzenon.cn/test")
    
    
    # browser.switch_to.window(browser.window_handles[-1]) # 切换到新打开的窗口
    step1()
    input()
    # 关闭浏览器
    browser.quit()